package com.chuzhiyun.chengguoxy.feature.internship.leave;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.GridLayoutManager;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chuzhiyun.chengguoxy.R;
import com.chuzhiyun.chengguoxy.databinding.FragmentLeaveInputBinding;
import com.chuzhiyun.chengguoxy.feature.base.BaseFragment;
import com.chuzhiyun.chengguoxy.feature.bean.WorkTagsImageBean;
import com.chuzhiyun.chengguoxy.network.NetApi;
import com.chuzhiyun.chengguoxy.network.NetService;
import com.chuzhiyun.chengguoxy.network.StringNetCallback;
import com.chuzhiyun.chengguoxy.utlis.CustomClickListener;
import com.chuzhiyun.chengguoxy.utlis.NewItemClickListener;
import com.chuzhiyun.chengguoxy.utlis.NewOnItemChildClickListener;
import com.chuzhiyun.chengguoxy.utlis.PictureSelectUtil;
import com.chuzhiyun.chengguoxy.utlis.StringUtils;
import com.chuzhiyun.chengguoxy.utlis.TimeUtils;
import com.chuzhiyun.chengguoxy.utlis.ToastCustom;
import com.codingending.popuplayout.PopupLayout;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarView;
import com.lzy.okgo.callback.StringCallback;
import com.shehuan.nicedialog.BaseNiceDialog;
import com.shehuan.nicedialog.NiceDialog;
import com.shehuan.nicedialog.ViewConvertListener;
import com.shehuan.nicedialog.ViewHolder;
import com.vondear.rxtool.RxFileTool;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

import static java.util.Objects.*;

@SuppressWarnings("FieldMayBeFinal")
public class LeaveInputFragment extends BaseFragment<FragmentLeaveInputBinding> {

    private List<WorkTagsImageBean> datas = new ArrayList<>();
    private LeaveInputFragment.MyAdapter myAdapter;

    private String leaveStartDate;
    private String leaveEndDate;
    private String reason;
    private String chooseTimeDate;

    public String projectId;
    private Boolean isEnd = false;//是否已经结束实习

    final @SuppressLint("SimpleDateFormat")
    SimpleDateFormat dateFormat  = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public void initView(View view) {
        binding.navView.ivBack.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                requireActivity().finish();
            }
        });
        binding.navView.tvTitle.setText("请假");
        initEditLength(binding.editLiyou,binding.tvLengthTip,200);

        WorkTagsImageBean bean = new WorkTagsImageBean();
        bean.setTagsType("0");
        datas.add(bean);

        binding.recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        myAdapter = new LeaveInputFragment.MyAdapter(R.layout.item_worktags_input, datas);
        binding.recyclerView.setAdapter(myAdapter);
        myAdapter.addChildClickViewIds(R.id.delete_Img);
        myAdapter.notifyDataSetChanged();

        myAdapter.setOnItemClickListener(new NewItemClickListener() {
            @Override
            protected void onSingleClick(BaseQuickAdapter adapter, View view, int position) {
                WorkTagsImageBean bean = datas.get(position);
                if (bean.getTagsType().equals("0"))
                {
                    getPhoto(requireActivity());
                }
            }
        });

        myAdapter.setOnItemChildClickListener(new NewOnItemChildClickListener() {
            @Override
            protected void onSingleClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.delete_Img) {
                    WorkTagsImageBean bean = datas.get(position);
                    if (bean.getTagsType().equals("1"))
                    {
                        datas.remove(position);
                        deleteImageList();
                        myAdapter.notifyDataSetChanged();
                    }
                }
            }
        });

        Bundle bundle = getArguments();
        projectId = bundle != null ? bundle.getString("projectId") : null;
//        String internshipStatus = bundle != null ? bundle.getString("internshipStatus") : null;
//        System.out.println(internshipStatus);
//        assert internshipStatus != null;
        String internshipStatus = "2";
        if (internshipStatus.equals("3")){
            isEnd = true;
        }else {
            isEnd = false;
        }

        Date date = new Date();
        String dateStr = dateFormat.format(date);
        binding.tvStartTime.setText(dateStr);
        binding.tvEndTime.setText(dateStr);
        leaveStartDate = dateStr;
        leaveEndDate = dateStr;

    }
    @Override
    public void initData() {

    }

    @Override
    public void setListener() {

        binding.tvStartTimeRl.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                if (isEnd){
                    ToastCustom.showErrorToast("实习已结束\n无法请假");
                    return;
                }
                showBottomTimeChoose("1");
            }

        });

        binding.tvEndTimeRl.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                if (isEnd){
                    ToastCustom.showErrorToast("实习已结束\n无法请假");
                    return;
                }
                showBottomTimeChoose("2");
            }

        });

        binding.editLiyou.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                reason = s.toString();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        binding.rlSubmit.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                if (StringUtils.isBlank(reason)){
                    ToastCustom.showErrorToast("请输入请假理由");
                    return;
                }

                String url = NetApi.postLeaveInfo();
                HashMap<String,String>param = new HashMap<>();
                param.put("reason",reason);
                param.put("start",leaveStartDate);
                param.put("end",leaveEndDate);
                ArrayList<File> pictures = new ArrayList<>();
                if (datas.size()>1)
                {
                    for (int i=0;i<datas.size();i++)
                    {
                        WorkTagsImageBean imageBran = datas.get(i);
                        if (imageBran.getTagsType().equals("1"))
                        {
                            pictures.add(imageBran.getImageFile());
                        }
                    }
                }
                showLoadingDialog();
                NetService.getInstance().postFileWithParam(url, param, pictures, new StringNetCallback() {
                    @Override
                    public void onSuccess(String response, int statusCode) throws Exception {
                        dismissLoadingDialog();
                        if (statusCode==201){
                            clearLeaveInfo();
                            ToastCustom.showSuccessToast("提交成功");
                            ((LeaveHomeActivity) requireActivity()).setCurrentIndex(1);
                        }
                    }

                    @Override
                    public void onError(String error) {
                        System.out.println(error);
                        dismissLoadingDialog();
                    }
                });
            }
        });
    }

    public static class MyAdapter extends BaseQuickAdapter<WorkTagsImageBean, BaseViewHolder> {
        public MyAdapter(int layoutResId, List<WorkTagsImageBean> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(@NotNull BaseViewHolder helper, WorkTagsImageBean item) {
            if (item.getTagsType().equals("1"))
            {
                Bitmap bitmap= BitmapFactory.decodeFile(item.getImageFile().toString());
                helper.setImageBitmap(R.id.tags_Img,bitmap);
                helper.setVisible(R.id.delete_Img,true);
            }
            else
            {
                helper.setImageResource(R.id.tags_Img,R.mipmap.add_work);
                helper.setVisible(R.id.delete_Img,false);
            }
        }
    }

    private void showBottomTimeChoose(String type){

        //时间选择器
        View view=View.inflate(getContext(),R.layout.timechoose_menu,null);
        PopupLayout popupLayout = PopupLayout.init(getContext(),view);
        popupLayout.show();

        TextView monthText = view.findViewById(R.id.month_Text);
        CalendarView calendarView = view.findViewById(R.id.calendarView);
        ImageView calendarLeft = view.findViewById(R.id.left_Text);
        ImageView calendarRight = view.findViewById(R.id.right_Text);
        calendarLeft.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                calendarView.scrollToPre();
            }

        });
        calendarRight.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                calendarView.scrollToNext();
            }

        });

        calendarView.setOnCalendarSelectListener(new CalendarView.OnCalendarSelectListener() {
            @Override
            public void onCalendarOutOfRange(Calendar calendar) {

            }

            @Override
            public void onCalendarSelect(Calendar calendar, boolean isClick) {
                String dateStr = null;
                try {
                    dateStr = TimeUtils.strToDateFormat(calendar.toString());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                String string = dateStr;
                Date nowDate = new Date();
                String nowDateStr = dateFormat.format(nowDate);
                boolean isBefore = TimeUtils.TimeCompare(string);
                if (isBefore)
                {
                    if (string.equals(nowDateStr)) {
                        chooseTimeDate = string;
                    }
                    else {
                        chooseTimeDate = "";
                        ToastCustom.showErrorToast("请假日期不能早于今天");
                    }
                }
                else {
                    chooseTimeDate = string;
                }
            }
        });

        java.util.Calendar calendar = java.util.Calendar.getInstance();
        int y = calendar.get(java.util.Calendar.YEAR);
        int m = calendar.get(java.util.Calendar.MONTH);

        @SuppressLint("SimpleDateFormat") SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月");
        calendar.setTime(new Date());
        String monthString = df.format(calendar.getTime());
        monthText.setText(monthString);
        calendarView.setOnMonthChangeListener(new CalendarView.OnMonthChangeListener() {
            @SuppressLint("DefaultLocale")
            @Override
            public void onMonthChange(int year, int month) {
                if (month<10)
                {
                    monthText.setText(String.format("%d年0%d月", year, month));
                }
                else
                {
                    monthText.setText(String.format("%d年%d月", year, month));
                }
            }
        });

        TextView cancelText = view.findViewById(R.id.cancel_Text);
        TextView sureText = view.findViewById(R.id.sure_Text);
        cancelText.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                popupLayout.dismiss();
            }

        });
        sureText.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                popupLayout.dismiss();
                if (type.equals("1")){
                    if (!StringUtils.isBlank(chooseTimeDate)){
                        binding.tvStartTime.setText(chooseTimeDate);
                        leaveStartDate = chooseTimeDate;
                    }
                }
                if (type.equals("2")){
                    if (!StringUtils.isBlank(chooseTimeDate)){
                        binding.tvEndTime.setText(chooseTimeDate);
                        leaveEndDate = chooseTimeDate;
                    }
                }
            }

        });
    }

    private void getPhoto(FragmentActivity myActivity) {

        NiceDialog.init()
                .setLayoutId(R.layout.dialog_head_img)
                .setConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                        holder.setOnClickListener(R.id.select_photo_dialog_btn_camera, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                                takePhotoCamera();
                            }
                        });
                        holder.setOnClickListener(R.id.select_photo_dialog_btn_album, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                                takePhotoAlbum();
                            }
                        });
                        holder.setOnClickListener(R.id.select_photo_dialog_btn_cancel, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                            }
                        });
                    }
                })
                .setGravity(Gravity.BOTTOM)
                .show(myActivity.getSupportFragmentManager());
    }

    private void takePhotoCamera() {
        PictureSelectUtil.with(this)
                .camera()
                .setCallback(new PictureSelectUtil.OnCallback() {
                    @Override
                    public void onCallback(Uri uri) {
                        File mFile = RxFileTool.getFilePhotoFromUri(getActivity(),uri);
                        WorkTagsImageBean bean = new WorkTagsImageBean();
                        bean.setImageFile(mFile);
                        bean.setTagsType("1");
                        datas.add(bean);
                        changeImageList();
                        myAdapter.notifyDataSetChanged();
                    }
                }).select();
    }

    private void takePhotoAlbum(){
        PictureSelectUtil.with(this)
                .gallery()
                .setCallback(new PictureSelectUtil.OnCallback() {
                    @Override
                    public void onCallback(Uri uri) {
                        File mFile = RxFileTool.getFilePhotoFromUri(getActivity(),uri);
                        WorkTagsImageBean bean = new WorkTagsImageBean();
                        bean.setImageFile(mFile);
                        bean.setTagsType("1");
                        datas.add(bean);
                        changeImageList();
                        myAdapter.notifyDataSetChanged();
                    }
                }).select();
    }

    private void changeImageList() {
        // 把name为haha的学生放在最后面
        WorkTagsImageBean temp = new WorkTagsImageBean();
        boolean flag = false;
        for(int i = 0; i < datas.size(); i++){
            WorkTagsImageBean student = datas.get(i);
            if (student.getTagsType().equals("0")) {
                temp = student;
                flag = true;
                datas.remove(i);
                break;
            }
        }
        if (flag) {
            if (datas.size()<4)
            {
                datas.add(temp);
            }
        }
    }

    private void deleteImageList() {
        boolean isFlag = false;
        for(int i = 0; i < datas.size(); i++){
            WorkTagsImageBean student = datas.get(i);
            if (student.getTagsType().equals("0")) {
                isFlag = true;
            }
        }
        if (!isFlag)
        {
            WorkTagsImageBean temp2 = new WorkTagsImageBean();
            temp2.setTagsType("0");
            datas.add(temp2);
        }
    }

    /*清空输入内容*/
    private void clearLeaveInfo() {
        Date date = new Date();
        String dateStr = dateFormat.format(date);
        binding.tvStartTime.setText(dateStr);
        binding.tvEndTime.setText(dateStr);
        leaveStartDate = dateStr;
        leaveEndDate = dateStr;
        reason="";
        binding.editLiyou.setText("");
        datas.clear();
        WorkTagsImageBean bean = new WorkTagsImageBean();
        bean.setTagsType("0");
        datas.add(bean);
        myAdapter.notifyDataSetChanged();
    }
}